class CheckoutManager {
    constructor() {
        this.items = new Map();
        this.init();
    }

    init() {
        this.initializeQuantityControls();
        this.initializeCheckboxes();
        this.setupFormValidation();
        this.loadCartItems();
    }

    loadCartItems() {
        const savedCart = localStorage.getItem('shopping-cart');
        if (savedCart) {
            const cartItems = JSON.parse(savedCart);
            cartItems.forEach(item => {
                const checkbox = document.querySelector(`input[value="${item.id}"]`);
                if (checkbox) {
                    checkbox.checked = true;
                    this.updateQuantity(item.id, item.quantity);
                }
            });
            this.updateTotalPrice();
        }
    }

    initializeQuantityControls() {
        document.querySelectorAll('.quantity-control').forEach(control => {
            const itemId = control.dataset.itemId;
            const input = control.querySelector('.quantity-input');
            const decreaseBtn = control.querySelector('.decrease-btn');
            const increaseBtn = control.querySelector('.increase-btn');

            this.items.set(itemId, {
                quantity: parseInt(input.value) || 1,
                price: parseFloat(control.dataset.price)
            });

            decreaseBtn.addEventListener('click', () => this.changeQuantity(itemId, -1));
            increaseBtn.addEventListener('click', () => this.changeQuantity(itemId, 1));
            input.addEventListener('change', () => this.validateQuantityInput(itemId, input));
        });
    }

    initializeCheckboxes() {
        document.querySelectorAll('input[type="checkbox"][name="goodsId"]').forEach(checkbox => {
            checkbox.addEventListener('change', () => this.updateTotalPrice());
        });
    }

    changeQuantity(itemId, delta) {
        const item = this.items.get(itemId);
        if (!item) return;

        const newQuantity = Math.max(1, item.quantity + delta);
        this.updateQuantity(itemId, newQuantity);
        this.updateTotalPrice();
    }

    updateQuantity(itemId, quantity) {
        const item = this.items.get(itemId);
        if (!item) return;

        item.quantity = quantity;
        const input = document.querySelector(`#count${itemId}`);
        if (input) {
            input.value = quantity;
        }
    }

    validateQuantityInput(itemId, input) {
        let value = parseInt(input.value);
        if (isNaN(value) || value < 1) {
            value = 1;
        }
        this.updateQuantity(itemId, value);
        this.updateTotalPrice();
    }

    updateTotalPrice() {
        let total = 0;
        document.querySelectorAll('input[type="checkbox"][name="goodsId"]').forEach(checkbox => {
            if (checkbox.checked) {
                const itemId = checkbox.value;
                const item = this.items.get(itemId);
                if (item) {
                    total += item.price * item.quantity;
                }
            }
        });

        const totalElement = document.querySelector('.total-price');
        if (totalElement) {
            totalElement.textContent = `¥${total.toFixed(2)}`;
        }

        // 更新结算按钮状态
        const checkoutBtn = document.querySelector('.checkout-btn');
        if (checkoutBtn) {
            const hasSelectedItems = Array.from(document.querySelectorAll('input[type="checkbox"][name="goodsId"]'))
                .some(checkbox => checkbox.checked);
            checkoutBtn.disabled = !hasSelectedItems;
        }
    }

    setupFormValidation() {
        const form = document.querySelector('#checkoutForm');
        if (!form) return;

        form.addEventListener('submit', (e) => {
            e.preventDefault();

            const selectedItems = Array.from(document.querySelectorAll('input[type="checkbox"][name="goodsId"]:checked'));
            if (selectedItems.length === 0) {
                this.showError('请至少选择一件商品');
                return;
            }

            // 构建提交数据
            const formData = new FormData();
            selectedItems.forEach(checkbox => {
                const itemId = checkbox.value;
                const item = this.items.get(itemId);
                if (item) {
                    formData.append('items[]', JSON.stringify({
                        id: itemId,
                        quantity: item.quantity
                    }));
                }
            });

            // 发送结算请求
            this.submitCheckout(formData);
        });
    }

    async submitCheckout(formData) {
        try {
            const response = await fetch(`${window.contextPath}/checkoutServlet`, {
                method: 'POST',
                body: formData
            });

            const result = await response.json();
            if (result.success) {
                // 清除本地购物车
                localStorage.removeItem('shopping-cart');
                // 显示成功消息
                this.showSuccess(result.message || '结算成功！');
                // 延迟跳转到订单确认页面
                setTimeout(() => {
                    window.location.href = `${window.contextPath}/orderConfirm.jsp`;
                }, 1500);
            } else {
                this.showError(result.message || '结算失败，请重试');
            }
        } catch (error) {
            console.error('Checkout error:', error);
            this.showError('发生错误，请稍后重试');
        }
    }

    showError(message) {
        const errorElement = document.querySelector('.error-message');
        if (errorElement) {
            errorElement.textContent = message;
            errorElement.style.display = 'block';
            setTimeout(() => {
                errorElement.style.display = 'none';
            }, 3000);
        }
    }

    showSuccess(message) {
        // 可以添加一个成功消息显示元素
        const successElement = document.createElement('div');
        successElement.className = 'success-message';
        successElement.textContent = message;
        document.querySelector('.container').prepend(successElement);
        setTimeout(() => {
            successElement.remove();
        }, 3000);
    }
}

document.addEventListener('DOMContentLoaded', function () {
    // 常量定义
    const API_ENDPOINTS = {
        CHECKOUT: '/checkoutServlet',
        ORDER_SUCCESS: '/orderSuccessServlet',
        SHOP_LIST: '/shopListServlet'
    };

    const BASE_URL = window.location.origin + '${pageContext.request.contextPath}';

    // 获取表单元素
    const checkoutForm = document.getElementById('checkoutForm');
    const receiverInput = document.getElementById('receiver');
    const phoneInput = document.getElementById('phone');
    const addressInput = document.getElementById('address');
    const totalAmountInput = document.getElementById('totalAmount');
    const submitBtn = document.querySelector('.submit-btn');

    // 验证规则
    const phoneRegex = /^1[3-9]\d{9}$/;
    const validationRules = {
        receiver: (value) => value.length >= 2,
        phone: (value) => phoneRegex.test(value),
        address: (value) => value.length >= 5
    };

    const errorMessages = {
        receiver: '收货人姓名至少需要2个字符',
        phone: '请输入正确的手机号码',
        address: '请输入详细的收货地址'
    };

    // 设置字段状态
    function setFieldStatus(input, isValid, message = '') {
        const formGroup = input.closest('.form-group');
        formGroup.classList.remove('error', 'success');

        let errorDiv = formGroup.querySelector('.error-message');
        if (!errorDiv) {
            errorDiv = document.createElement('div');
            errorDiv.className = 'error-message';
            formGroup.appendChild(errorDiv);
        }

        if (!isValid) {
            formGroup.classList.add('error');
            errorDiv.textContent = message;
        } else {
            formGroup.classList.add('success');
            errorDiv.textContent = '';
        }
    }

    // 验证单个输入
    function validateInput(input, validationFn, errorMessage) {
        const value = input.value.trim();
        const isValid = validationFn(value);
        setFieldStatus(input, isValid, isValid ? '' : errorMessage);
        return isValid;
    }

    // 添加实时验证
    [receiverInput, phoneInput, addressInput].forEach(input => {
        ['input', 'blur'].forEach(eventType => {
            input.addEventListener(eventType, () => {
                validateInput(
                    input,
                    validationRules[input.id],
                    errorMessages[input.id]
                );
            });
        });
    });

    // 格式化手机号码
    phoneInput.addEventListener('input', function (e) {
        let value = e.target.value.replace(/\D/g, '');
        if (value.length > 11) {
            value = value.slice(0, 11);
        }
        e.target.value = value;
    });

    // 提交订单处理
    async function submitOrder(formData) {
        try {
            submitBtn.disabled = true;
            submitBtn.textContent = '正在提交...';

            const response = await fetch(BASE_URL + API_ENDPOINTS.CHECKOUT, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(Object.fromEntries(formData))
            });

            const data = await response.json();

            if (data.success) {
                showToast('订单提交成功！', 'success');
                setTimeout(() => {
                    window.location.href = BASE_URL + API_ENDPOINTS.ORDER_SUCCESS;
                }, 1500);
            } else {
                throw new Error(data.message || '订单提交失败');
            }
        } catch (error) {
            showToast(error.message || '提交订单时发生错误，请重试', 'error');
            submitBtn.disabled = false;
            submitBtn.textContent = '提交订单';
        }
    }

    // 显示提示信息
    function showToast(message, type = 'info') {
        const toast = document.createElement('div');
        toast.className = `toast toast-${type}`;
        toast.textContent = message;
        document.body.appendChild(toast);

        setTimeout(() => {
            toast.classList.add('show');
        }, 100);

        setTimeout(() => {
            toast.classList.remove('show');
            setTimeout(() => toast.remove(), 300);
        }, 3000);
    }

    // 表单提交处理
    checkoutForm.addEventListener('submit', async function (e) {
        e.preventDefault();

        // 验证所有字段
        const validationResults = [
            validateInput(receiverInput, validationRules.receiver, errorMessages.receiver),
            validateInput(phoneInput, validationRules.phone, errorMessages.phone),
            validateInput(addressInput, validationRules.address, errorMessages.address)
        ];

        if (validationResults.every(Boolean)) {
            const formData = new FormData();
            formData.append('receiver', receiverInput.value.trim());
            formData.append('phone', phoneInput.value.trim());
            formData.append('address', addressInput.value.trim());
            formData.append('totalAmount', totalAmountInput.value);

            const orderDetails = {
                totalAmount: totalAmountInput.value,
                receiver: receiverInput.value.trim(),
                phone: phoneInput.value.trim(),
                address: addressInput.value.trim()
            };

            const confirmMessage = `确认提交订单？\n订单总额：¥${orderDetails.totalAmount}\n收货人：${orderDetails.receiver}\n手机号码：${orderDetails.phone}\n收货地址：${orderDetails.address}`;

            if (confirm(confirmMessage)) {
                await submitOrder(formData);
            }
        } else {
            const firstError = document.querySelector('.form-group.error');
            if (firstError) {
                firstError.scrollIntoView({behavior: 'smooth', block: 'center'});
            }
        }
    });

    // 返回购物车
    document.addEventListener('click', function (e) {
        if (e.target.matches('.back-to-cart')) {
            e.preventDefault();
            window.location.href = BASE_URL + '/shopCartServlet';
        }
    });

    // 添加CSS样式
    const style = document.createElement('style');
    style.textContent = `
        .toast {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 12px 24px;
            border-radius: 4px;
            background: #fff;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
            transform: translateX(120%);
            transition: transform 0.3s ease;
            z-index: 1000;
        }

        .toast.show {
            transform: translateX(0);
        }

        .toast-success {
            background: #4caf50;
            color: white;
        }

        .toast-error {
            background: #f44336;
            color: white;
        }
    `;
    document.head.appendChild(style);
});

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    const checkoutManager = new CheckoutManager();
});
